#include<iostream>
#include<string>
#include<cstring>
#include<cassert>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;

int main()
{
    int pipefd[2] = {0};
    int res = pipe(pipefd);
    assert(res != -1);

    //条件编译，当为debug时才会执行
#ifdef DEBUG
    cout << "pipefd[0]: " << pipefd[0] << endl;
    cout << "pipefd[1]: " << pipefd[1] << endl;
#endif

    pid_t id = fork();      //返回值是pid_t，不要写错
    assert(id != -1);

    if(id == 0)
    {
        //cout<<"snow"<<endl;
        close(pipefd[1]);           //不要关闭错误，是数组而不是单独的1
        char receive_buff[1024] = {0};
        //cout<<"snow"<<endl;
        while(true)
        {
            //sleep(5);
            //cout<<"snow"<<endl;
            ssize_t s = read(pipefd[0], receive_buff, sizeof(receive_buff) - 1);        //大小减去一，留个位置给\0
            //cout<<s<<endl;
            if(s == 0)
            {
                cout << "write over, i over" << endl;
                break;
            }
            receive_buff[s] = 0;
            cout << "child receive, pid=" << getpid() << ",father said: " << receive_buff << endl;
            //cout<<strlen(receive_buff)<<endl;

            //读关，写继续写，写进程被系统终止
            //记得加退出循环的语句，否则执行，ctrl+c将会无法关闭
            // // close(pipefd[0]);
            // // sleep(5);
            // // break;
        }

        exit(0);
    }
    close(pipefd[0]);           //不要关闭错误，是数组而不是单独的0
    int cnt = 0;
    string s = "snow dragon writed";
    char send_buff[1024] = {0};
    //while(true)
    while(cnt < 6)
    {
        snprintf(send_buff, sizeof(send_buff), "%s : %d", s.c_str(), cnt++);
        //cout << send_buff << endl;
        //ssize_t s = write(pipefd[1], send_buff, strlen(send_buff));
        write(pipefd[1], send_buff, strlen(send_buff));
        //cout<<s<<endl;
        //sleep(5);
        sleep(1);
    }
    close(pipefd[1]);
    cout << "write over" << endl;
    pid_t ret = waitpid(id, nullptr, 0);
    cout << "wait sucess, id= " << id << ", ret= " << ret << endl;        //把id也打印出来，打全
    assert(ret > 0);        //加上断言，更加严谨

    return 0;
}